package com.itheima.tliaswebmanagement.aop;


import com.itheima.tliaswebmanagement.controller.CurrentHolder;
import com.itheima.tliaswebmanagement.mapper.OperateLogMapper;
import com.itheima.tliaswebmanagement.pojo.OperateLog;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.tliaswebmanagement.annotation.OperationLog)")
    public Object insertLog (ProceedingJoinPoint pjp) throws Throwable {
        //记录开始时间
        long begin = System.currentTimeMillis();

        //获取执行方法的名称
        String methodName = pjp.getSignature().getName();
        //获取对象的类名称
        String className = pjp.getTarget().getClass().getName();
        //获取方法的参数
        Object[] argsName = pjp.getArgs();
        String args = Arrays.toString(argsName);
        //执行方法
        Object result = pjp.proceed();
        //当前时间
        long end = System.currentTimeMillis();
        //耗时
        long cost = end - begin;

        //构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams( args);
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime( cost);
        //保存日志
        operateLogMapper.insert(operateLog);
        return result;
    }

    private Integer getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}
